package com.huidu.bitrade.controller;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huidu.bitrade.entity.Member;
import com.huidu.bitrade.entity.MemberGroup;
import com.huidu.bitrade.entity.MemberHdc;
import com.huidu.bitrade.entity.MemberWallet;
import com.huidu.bitrade.mapper.MemberHdcMapper;
import com.huidu.bitrade.mapper.MemberMapper;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.util.FileUtil;
import com.huidu.bitrade.util.MessageResult;
import com.huidu.bitrade.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;


@Api(tags = "查询所有下级")
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/test")
public class TestController {

    private final MemberGroupService memberGroupService;
    private final MemberMapper memberMapper;
    private final MemberWalletService memberWalletService;
    private final NewMemberService memberService;
    private final MemberHdcMapper memberHdcMapper;

    @ApiOperation("导出团队数据")
    @PostMapping("/testExport")
    public MessageResult testExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<MemberGroup> list = memberGroupService.list();
        if(CollectionUtils.isEmpty(list)){
            return MessageResult.error("导出数据为空");
        }
        return new FileUtil().exportExcel(request, response, list, "childList");
    }

    @ApiOperation("插入团队数据")
    @PostMapping("/insertAll")
    public MessageResult insertAll(@RequestParam(required = false) Long memberId){
        List<MemberGroup> list = memberGroupService.selectMemberChild(memberId);
        memberGroupService.saveBatch(list);
        return MessageResult.success("111",null);
    }

    @ApiOperation("更新团队余额数据")
    @PostMapping("/updateAll")
    public MessageResult updateAll(){
        List<MemberGroup> list = memberGroupService.list();
        List<MemberGroup> updateList = new ArrayList<>();
        //查询余额数据
        List<MemberBalanceVo> balanceVos = memberGroupService.selectMemberBalance();
        Map<Long,List<MemberBalanceVo>> balanceVoMap = balanceVos.stream().collect(Collectors.groupingBy(MemberBalanceVo::getMemberId));
        //查询hdz质押数据
        List<MemberHdzVo> hdzVos = memberGroupService.selectHdzOrder();
        Map<Long,MemberHdzVo> hdzMap = hdzVos.stream().collect(Collectors.toMap(MemberHdzVo::getMemberId, Function.identity()));
        for(MemberGroup memberGroup:list){
            List<MemberBalanceVo> memberBalanceVos = balanceVoMap.get(memberGroup.getMemberId());
            MemberHdzVo memberHdzVo = hdzMap.get(memberGroup.getMemberId());
            if(CollectionUtils.isEmpty(memberBalanceVos)&&Objects.isNull(memberHdzVo)){
                continue;
            }
            if(CollectionUtils.isNotEmpty(memberBalanceVos)){
                for(MemberBalanceVo vo:memberBalanceVos){
                    switch (vo.getCoinId()){
                        case "HDC":
                            memberGroup.setHdc(vo.getBalance());
                            memberGroup.setLockNumber(vo.getToReleased());
                            break;
                        case "HDZ":
                            memberGroup.setHdz(vo.getBalance());
                            break;
                        case "CNHD":
                            memberGroup.setCnhd(vo.getBalance());
                            break;
                    }
                }
            }
            if(Objects.nonNull(memberHdzVo)){
                memberGroup.setLoanNumber(memberHdzVo.getNumber());
            }
            updateList.add(memberGroup);
        }
        memberGroupService.updateBatchById(updateList);
        return MessageResult.success("111",null);
    }

    @ApiOperation("清空团队余额")
    @PostMapping("/clean")
    public MessageResult clean(){
        memberGroupService.walletClean();
        return MessageResult.success("success");
    }

    @ApiOperation("修改用户hdc数据")
    @PostMapping("/updateHdc")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult updateHdc(){
        //所有用户
        List<Long> list = memberService.getUpdateHdcMember();
        for(Long memberId:list){
            //查询正在挂单数据
            BigDecimal exchange = memberMapper.getExchange(memberId);
            //查询正在提现的
            BigDecimal withdraw = memberMapper.getWithdraw(memberId);
            if(exchange.compareTo(BigDecimal.ZERO)<=0 && withdraw.compareTo(BigDecimal.ZERO)<=0){
                continue;
            }
            //查询手续费
            BigDecimal fee = memberMapper.getFee(memberId);
            //查询得到奖励
            BigDecimal award = memberMapper.getAward(memberId);
            //应该冻结
            BigDecimal systemFrozen = award.subtract(fee);
            //查询钱包
            MemberWallet memberWallet = memberWalletService.findByCoinUnitAndMemberId("HDC",memberId);
            //总金额
            BigDecimal totalBalance = memberWallet.getBalance().add(memberWallet.getSystemFrozen()).add(memberWallet.getFrozenBalance());
            //计算系统冻结应该改为多少
            BigDecimal system = systemFrozen.compareTo(BigDecimal.ZERO)>=0?systemFrozen:memberWallet.getSystemFrozen();

            //计算冻结应该改为多少
            BigDecimal frozen = withdraw.add(exchange);
            //计算余额应该为多少
            BigDecimal balance = totalBalance.subtract(system).subtract(frozen);
            memberWallet.setBalance(balance.compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:balance);
            memberWallet.setFrozenBalance(frozen);
            memberWallet.setSystemFrozen(system);
            memberWalletService.save(memberWallet);
            memberHdcMapper.insert(MemberHdc.builder()
                    .balance(balance)
                    .frozenBalance(frozen)
                    .systemFrozen(system)
                    .exchange(exchange)
                    .fee(fee)
                    .memberId(memberId)
                    .withdraw(withdraw)
                    .award(award).build());
        }
        return MessageResult.success("111",null);
    }

}
